package com.governtalk.backend.service.impl;

import com.governtalk.backend.dto.question.QuestionDto;
import com.governtalk.backend.dto.question.QuestionCategoryDto;
import com.governtalk.backend.dto.question.QuestionOptionDto;
import com.governtalk.backend.entity.Question;
import com.governtalk.backend.entity.QuestionCategory;
import com.governtalk.backend.entity.QuestionOption;
import com.governtalk.backend.repository.QuestionRepository;
import com.governtalk.backend.repository.QuestionCategoryRepository;
import com.governtalk.backend.repository.QuestionOptionRepository;
import com.governtalk.backend.repository.SearchHistoryRepository;
import com.governtalk.backend.entity.SearchHistory;
import com.governtalk.backend.service.QuestionService;
import com.governtalk.backend.service.WrongQuestionService;
import com.governtalk.backend.dto.wrongquestion.WrongQuestionDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {
    
    @Autowired
    private QuestionRepository questionRepository;
    
    @Autowired
    private QuestionCategoryRepository categoryRepository;
    
    @Autowired
    private QuestionOptionRepository optionRepository;
    
    @Autowired
    private SearchHistoryRepository searchHistoryRepository;
    
    @Autowired
    private WrongQuestionService wrongQuestionService;
    
    @Override
    public List<QuestionCategoryDto> getQuestionCategories() {
        List<QuestionCategory> categories = categoryRepository.findByParentIdIsNull();
        return categories.stream().map(category -> {
            QuestionCategoryDto dto = convertCategoryToDto(category);
            // 统计该分类下的题目数量
            long questionCount = questionRepository.countByCategoryId(category.getId());
            dto.setQuestionCount((int) questionCount);
            return dto;
        }).collect(Collectors.toList());
    }
    
    @Override
    public Page<QuestionDto> searchQuestions(String keyword, String type, String difficulty, 
                                           Long categoryId, String sortBy, String sortOrder, Pageable pageable) {
        System.out.println("=== 题目搜索API调用 ===");
        System.out.println("搜索关键词: " + keyword);
        System.out.println("题目类型: " + type);
        System.out.println("难度等级: " + difficulty);
        System.out.println("分类ID: " + categoryId);
        System.out.println("分页信息: 页码=" + pageable.getPageNumber() + ", 大小=" + pageable.getPageSize());
        
        Page<Question> questions;
        
        // 为了支持前端编辑距离算法，优先返回所有公开题目
        // 只有在有明确的筛选条件时才进行后端筛选
        if (categoryId != null) {
            System.out.println("按分类筛选: " + categoryId);
            questions = questionRepository.findByCategoryId(categoryId, pageable);
        } else if (type != null && !type.isEmpty()) {
            System.out.println("按类型筛选: " + type);
            questions = questionRepository.findByType(Question.QuestionType.valueOf(type.toUpperCase()), pageable);
        } else if (difficulty != null && !difficulty.isEmpty()) {
            System.out.println("按难度筛选: " + difficulty);
            questions = questionRepository.findByDifficulty(Question.DifficultyLevel.valueOf(difficulty.toUpperCase()), pageable);
        } else {
            // 默认返回所有公开题目，供前端编辑距离算法处理
            System.out.println("返回所有公开题目供前端编辑距离搜索");
            // 使用较大的页面大小来获取更多题目
            Pageable largePageable = PageRequest.of(0, 1000); // 获取前1000道题目
            questions = questionRepository.findByIsPublicTruePage(largePageable);
        }
        
        System.out.println("返回题目数量: " + questions.getTotalElements());
        System.out.println("=== 题目搜索API完成 ===");
        return questions.map(this::convertToDto);
    }
    
    @Override
    public QuestionDto getQuestionDetail(Long questionId) {
        Question question = questionRepository.findById(questionId)
                .orElseThrow(() -> new RuntimeException("Question not found"));
        return convertToDto(question);
    }
    
    @Override
    public Map<String, Object> submitAnswer(Long questionId, Map<String, Object> answer) {
        Question question = questionRepository.findById(questionId)
                .orElseThrow(() -> new RuntimeException("Question not found"));
        
        List<QuestionOption> correctOptions = optionRepository.findByQuestionIdAndIsCorrectTrue(questionId);
        
        boolean isCorrect = false;
        String explanation = question.getExplanation();
        
        if (question.getType() == Question.QuestionType.SINGLE_CHOICE) {
            Long selectedOptionId = Long.valueOf(answer.get("optionId").toString());
            isCorrect = correctOptions.stream()
                    .anyMatch(option -> option.getId().equals(selectedOptionId));
        } else if (question.getType() == Question.QuestionType.MULTIPLE_CHOICE) {
            @SuppressWarnings("unchecked")
            List<Long> selectedOptionIds = (List<Long>) answer.get("optionIds");
            Set<Long> correctIds = correctOptions.stream()
                    .map(QuestionOption::getId)
                    .collect(Collectors.toSet());
            Set<Long> selectedIds = new HashSet<>(selectedOptionIds);
            isCorrect = correctIds.equals(selectedIds);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("isCorrect", isCorrect);
        result.put("score", isCorrect ? 100 : 0);
        result.put("explanation", explanation);
        result.put("correctAnswer", correctOptions.stream()
                .map(QuestionOption::getContent)
                .collect(Collectors.toList()));
        
        return result;
    }
    
    @Override
    public void favoriteQuestion(Long questionId) {
        // 这里需要实现收藏题目逻辑
    }
    
    @Override
    public Page<QuestionDto> getFavoriteQuestions(Pageable pageable) {
        // 这里需要实现获取收藏题目逻辑
        return Page.empty();
    }
    
    @Override
    public Page<Map<String, Object>> getAnswerHistory(Pageable pageable) {
        // 这里需要实现获取答题历史逻辑
        return Page.empty();
    }
    
    @Override
    public QuestionDto createQuestion(QuestionDto questionDto) {
        Question question = Question.builder()
                .content(questionDto.getContent())
                .type(Question.QuestionType.valueOf(questionDto.getType().toUpperCase()))
                .difficulty(Question.DifficultyLevel.valueOf(questionDto.getDifficulty().toUpperCase()))
                .explanation(questionDto.getExplanation())
                .categoryId(questionDto.getCategoryId())
                .maxScore(questionDto.getMaxScore())
                .isPublic(questionDto.getIsPublic())
                .isOfficial(questionDto.getIsOfficial())
                .build();
        
        Question savedQuestion = questionRepository.save(question);
        
        // 保存选项
        if (questionDto.getOptions() != null) {
            for (QuestionOptionDto optionDto : questionDto.getOptions()) {
                QuestionOption option = QuestionOption.builder()
                        .question(savedQuestion)
                        .content(optionDto.getContent())
                        .isCorrect(optionDto.getIsCorrect())
                        .build();
                optionRepository.save(option);
            }
        }
        
        return convertToDto(savedQuestion);
    }
    
    @Override
    public QuestionDto updateQuestion(Long questionId, QuestionDto questionDto) {
        Question question = questionRepository.findById(questionId)
                .orElseThrow(() -> new RuntimeException("Question not found"));
        
        question.setContent(questionDto.getContent());
        question.setType(Question.QuestionType.valueOf(questionDto.getType().toUpperCase()));
        question.setDifficulty(Question.DifficultyLevel.valueOf(questionDto.getDifficulty().toUpperCase()));
        question.setExplanation(questionDto.getExplanation());
        question.setCategoryId(questionDto.getCategoryId());
        question.setMaxScore(questionDto.getMaxScore());
        question.setIsPublic(questionDto.getIsPublic());
        question.setIsOfficial(questionDto.getIsOfficial());
        question.setUpdatedAt(LocalDateTime.now());
        
        Question savedQuestion = questionRepository.save(question);
        return convertToDto(savedQuestion);
    }
    
    @Override
    public void deleteQuestion(Long questionId) {
        questionRepository.deleteById(questionId);
    }
    
    @Override
    public Map<String, Object> importQuestions(MultipartFile file) {
        // 这里需要实现导入题目逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("importedCount", 0);
        result.put("failedCount", 0);
        return result;
    }
    
    private QuestionDto convertToDto(Question question) {
        System.out.println("=== 转换题目为DTO ===");
        System.out.println("题目ID: " + question.getId());
        System.out.println("题目内容: " + question.getContent());
        System.out.println("题目类型: " + question.getType());
        
        // 确保选项被正确加载
        List<QuestionOption> options;
        if (question.getOptions() != null && !question.getOptions().isEmpty()) {
            // 如果JPA关联已经加载了选项，直接使用
            options = question.getOptions();
            System.out.println("使用JPA关联的选项，数量: " + options.size());
        } else {
            // 否则单独查询选项
            options = optionRepository.findByQuestionId(question.getId());
            System.out.println("单独查询选项，数量: " + options.size());
        }
        
        List<QuestionOptionDto> optionDtos = options.stream()
                .map(option -> {
                    System.out.println("选项: " + option.getContent() + " (正确: " + option.getIsCorrect() + ")");
                    return QuestionOptionDto.builder()
                            .id(option.getId())
                            .content(option.getContent())
                            .isCorrect(option.getIsCorrect())
                            .build();
                })
                .collect(Collectors.toList());
        
        System.out.println("最终选项DTO数量: " + optionDtos.size());
        
        return QuestionDto.builder()
                .id(question.getId())
                .content(question.getContent())
                .type(question.getType().name())
                .difficulty(question.getDifficulty().name())
                .categoryId(question.getCategoryId())
                .options(optionDtos)
                .explanation(question.getExplanation())
                .maxScore(question.getMaxScore())
                .isPublic(question.getIsPublic())
                .isOfficial(question.getIsOfficial())
                .imageUrl(question.getImageUrl())
                .createdAt(question.getCreatedAt())
                .updatedAt(question.getUpdatedAt())
                .build();
    }
    
    private QuestionCategoryDto convertCategoryToDto(QuestionCategory category) {
        return QuestionCategoryDto.builder()
                .id(category.getId())
                .name(category.getName())
                .description(category.getDescription())
                .parentId(category.getParentId())
                .createdAt(category.getCreatedAt())
                .updatedAt(category.getUpdatedAt())
                .build();
    }
    
    private Question.DifficultyLevel mapDifficultyToEnum(Integer difficulty) {
        if (difficulty == null) return null;
        switch (difficulty) {
            case 1: return Question.DifficultyLevel.EASY;
            case 2: return Question.DifficultyLevel.MEDIUM;
            case 3: return Question.DifficultyLevel.HARD;
            default: return Question.DifficultyLevel.MEDIUM;
        }
    }
    
    private Question.QuestionType mapTypeToEnum(String type) {
        if (type == null) return null;
        switch (type.toUpperCase()) {
            case "SINGLE_CHOICE": return Question.QuestionType.SINGLE_CHOICE;
            case "MULTIPLE_CHOICE": return Question.QuestionType.MULTIPLE_CHOICE;
            case "TRUE_FALSE": return Question.QuestionType.TRUE_FALSE;
            case "FILL_BLANK": return Question.QuestionType.FILL_BLANK;
            case "ESSAY": return Question.QuestionType.ESSAY;
            case "SHORT_ANSWER": return Question.QuestionType.SHORT_ANSWER;
            default: return Question.QuestionType.SINGLE_CHOICE;
        }
    }
    
    /**
     * 从题目列表中随机选择指定数量的题目
     */
    private List<Question> getRandomQuestions(List<Question> allQuestions, Integer count) {
        if (allQuestions == null || allQuestions.isEmpty()) {
            System.out.println("getRandomQuestions: 输入题目列表为空");
            return new ArrayList<>();
        }
        
        System.out.println("getRandomQuestions: 输入题目数量=" + allQuestions.size() + ", 需要数量=" + count);
        System.out.println("getRandomQuestions: 输入题目ID列表=" + allQuestions.stream().map(Question::getId).collect(Collectors.toList()));
        
        // 如果题目数量小于等于需要的数量，直接返回所有题目
        if (allQuestions.size() <= count) {
            System.out.println("题目数量不足，返回所有 " + allQuestions.size() + " 道题目");
            return new ArrayList<>(allQuestions);
        }
        
        // 创建题目列表的副本
        List<Question> questionList = new ArrayList<>(allQuestions);
        System.out.println("getRandomQuestions: 复制后的题目ID列表=" + questionList.stream().map(Question::getId).collect(Collectors.toList()));
        
        // 使用Collections.shuffle进行随机打乱
        Collections.shuffle(questionList);
        System.out.println("getRandomQuestions: shuffle后的题目ID列表=" + questionList.stream().map(Question::getId).collect(Collectors.toList()));
        
        // 返回前count个题目
        List<Question> selectedQuestions = questionList.subList(0, count);
        System.out.println("getRandomQuestions: 最终选择的题目ID列表=" + selectedQuestions.stream().map(Question::getId).collect(Collectors.toList()));
        System.out.println("从 " + allQuestions.size() + " 道题目中随机选择了 " + selectedQuestions.size() + " 道题目");
        
        return selectedQuestions;
    }
    
    @Override
    public List<QuestionDto> getPracticeQuestions(Long categoryId, Integer difficulty, String type, Integer count) {
        System.out.println("=== 获取练习题目 ===");
        System.out.println("categoryId: " + categoryId);
        System.out.println("difficulty: " + difficulty);
        System.out.println("type: " + type);
        System.out.println("count: " + count);
        
        // 构建查询条件
        List<Question> questions;
        
        try {
            // 先尝试获取所有公开题目，看看数据库中有多少题目
            List<Question> allQuestions = questionRepository.findByIsPublicTrue(PageRequest.of(0, 100));
            System.out.println("数据库中总共有 " + allQuestions.size() + " 道公开题目");
            
            if (allQuestions.isEmpty()) {
                System.out.println("数据库中没有公开题目！");
                return new ArrayList<>();
            }
            
            if (type != null) {
                // 优先按类型筛选，确保只返回指定类型的题目
                Question.QuestionType questionType = mapTypeToEnum(type);
                System.out.println("=== 题目类型筛选开始 ===");
                System.out.println("接收到的类型参数: " + type);
                System.out.println("转换后的枚举类型: " + questionType);
                System.out.println("分类ID: " + categoryId);
                System.out.println("难度: " + difficulty);
                System.out.println("题目数量: " + count);
                
                List<Question> allMatchingQuestions;
                if (categoryId != null && difficulty != null) {
                // 按分类、难度、类型筛选
                Question.DifficultyLevel difficultyLevel = mapDifficultyToEnum(difficulty);
                System.out.println("按分类、难度、类型筛选: " + categoryId + ", " + difficultyLevel + ", " + questionType);
                    allMatchingQuestions = questionRepository.findByCategoryIdAndDifficultyAndTypeAndIsPublicTrue(
                        categoryId, difficultyLevel, questionType, PageRequest.of(0, 1000)
                    );
                    System.out.println("查询结果数量: " + allMatchingQuestions.size());
                    if (!allMatchingQuestions.isEmpty()) {
                        System.out.println("查询结果中的题目类型分布:");
                        for (Question q : allMatchingQuestions) {
                            System.out.println("ID=" + q.getId() + ", 类型=" + q.getType() + ", 分类=" + q.getCategoryId() + ", 难度=" + q.getDifficulty());
                        }
                    }
                } else if (categoryId != null) {
                    // 按分类、类型筛选
                    System.out.println("按分类、类型筛选: " + categoryId + ", " + questionType);
                    allMatchingQuestions = questionRepository.findByCategoryIdAndTypeAndIsPublicTrue(
                        categoryId, questionType, PageRequest.of(0, 1000)
                    );
                } else if (difficulty != null) {
                    // 按难度、类型筛选
                    Question.DifficultyLevel difficultyLevel = mapDifficultyToEnum(difficulty);
                    System.out.println("按难度、类型筛选: " + difficultyLevel + ", " + questionType);
                    allMatchingQuestions = questionRepository.findByDifficultyAndTypeAndIsPublicTrue(
                        difficultyLevel, questionType, PageRequest.of(0, 1000)
                    );
                } else {
                    // 只按类型筛选
                    System.out.println("只按类型筛选: " + questionType);
                    allMatchingQuestions = questionRepository.findByTypeAndIsPublicTrue(
                        questionType, PageRequest.of(0, 1000)
                    );
                }
                System.out.println("筛选到的匹配题目数量: " + allMatchingQuestions.size());
                
                // 验证筛选结果，确保所有题目都是指定类型
                for (Question q : allMatchingQuestions) {
                    if (!q.getType().equals(questionType)) {
                        System.out.println("警告：发现类型不匹配的题目 ID=" + q.getId() + ", 期望类型=" + questionType + ", 实际类型=" + q.getType());
                    }
                }
                
                System.out.println("getRandomQuestions前 allMatchingQuestions 列表 (ID): " + allMatchingQuestions.stream().map(Question::getId).collect(Collectors.toList()));
                questions = getRandomQuestions(allMatchingQuestions, count);
                System.out.println("getRandomQuestions后返回的题目数量: " + questions.size());
                System.out.println("getRandomQuestions后 questions 列表 (ID): " + questions.stream().map(Question::getId).collect(Collectors.toList()));
        System.out.println("getRandomQuestions后题目类型分布:");
        for (Question q : questions) {
            System.out.println("ID=" + q.getId() + ", 类型=" + q.getType() + ", 内容=" + q.getContent().substring(0, Math.min(30, q.getContent().length())) + "...");
        }
                
                // 强制类型检查，确保所有题目都是指定类型
                List<Question> filteredQuestions = new ArrayList<>();
                for (Question q : questions) {
                    if (q.getType().equals(questionType)) {
                        filteredQuestions.add(q);
                    } else {
                        System.out.println("警告：过滤掉类型不匹配的题目 ID=" + q.getId() + ", 期望类型=" + questionType + ", 实际类型=" + q.getType());
                    }
                }
                questions = filteredQuestions;
                System.out.println("强制类型检查后题目数量: " + questions.size());
                
                if (!questions.isEmpty()) {
                    System.out.println("过滤后最终返回的题目数量: " + questions.size());
                    System.out.println("第一道题目的类型: " + questions.get(0).getType());
                    System.out.println("第一道题目的ID: " + questions.get(0).getId());
                    System.out.println("第一道题目的内容: " + questions.get(0).getContent());
                } else {
                    System.out.println("警告：没有找到任何匹配的题目！");
                }
            } else if (categoryId != null && difficulty != null) {
                // 按分类、难度筛选
                Question.DifficultyLevel difficultyLevel = mapDifficultyToEnum(difficulty);
                System.out.println("按分类、难度筛选: " + categoryId + ", " + difficultyLevel);
                List<Question> allMatchingQuestions = questionRepository.findByCategoryIdAndDifficultyAndIsPublicTrue(
                    categoryId, difficultyLevel, PageRequest.of(0, 1000)
                );
                questions = getRandomQuestions(allMatchingQuestions, count);
            } else if (categoryId != null) {
                // 按分类筛选
                System.out.println("按分类筛选: " + categoryId);
                List<Question> allMatchingQuestions = questionRepository.findByCategoryIdAndIsPublicTrue(categoryId, PageRequest.of(0, 1000));
                questions = getRandomQuestions(allMatchingQuestions, count);
            } else {
                // 随机获取题目
                System.out.println("随机获取题目");
                questions = getRandomQuestions(allQuestions, count);
            }
            
            System.out.println("筛选后得到 " + questions.size() + " 道题目");
            
        } catch (Exception e) {
            System.out.println("查询失败，使用所有公开题目: " + e.getMessage());
            e.printStackTrace();
            // 如果查询失败，返回所有公开题目
            questions = questionRepository.findByIsPublicTrue(PageRequest.of(0, count));
        }
        
        // 如果筛选结果不足，补充同类型的随机题目
        if (questions.size() < count && type != null) {
            System.out.println("筛选结果不足，尝试补充同类型的随机题目");
            Question.QuestionType questionType = mapTypeToEnum(type);
            List<Question> additionalQuestions = questionRepository.findByTypeAndIsPublicTrue(questionType, PageRequest.of(0, 1000));
            Set<Long> existingIds = questions.stream().map(Question::getId).collect(Collectors.toSet());
            List<Question> filteredAdditional = additionalQuestions.stream()
                .filter(q -> !existingIds.contains(q.getId()))
                .limit(count - questions.size())
                .collect(Collectors.toList());
            questions.addAll(filteredAdditional);
            System.out.println("补充了 " + filteredAdditional.size() + " 道同类型随机题目，总共 " + questions.size() + " 道题目");
        } else if (questions.size() < count) {
            System.out.println("筛选结果不足，但未指定类型，无法补充题目");
        }
        
        return questions.stream()
            .map(this::convertToDto)
            .collect(Collectors.toList());
    }
    
    @Override
    public Map<String, Object> submitPracticeAnswers(Map<String, Object> data) {
        try {
            System.out.println("=== 提交练习答案开始 ===");
            System.out.println("接收到的数据: " + data);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> answers = (List<Map<String, Object>>) data.get("answers");
            
            if (answers == null || answers.isEmpty()) {
                System.out.println("错误：答案列表为空");
                throw new RuntimeException("答案列表不能为空");
            }
            
            System.out.println("答案数量: " + answers.size());
            
            int correctCount = 0;
            int totalCount = answers.size();
            List<Map<String, Object>> analysis = new ArrayList<>();
        
        for (Map<String, Object> answerData : answers) {
            System.out.println("处理答案数据: " + answerData);
            
            Object questionIdObj = answerData.get("questionId");
            Object userAnswer = answerData.get("answer");
            
            System.out.println("questionId对象: " + questionIdObj + " (类型: " + (questionIdObj != null ? questionIdObj.getClass().getSimpleName() : "null") + ")");
            System.out.println("userAnswer对象: " + userAnswer + " (类型: " + (userAnswer != null ? userAnswer.getClass().getSimpleName() : "null") + ")");
            
            if (questionIdObj == null) {
                System.out.println("错误：questionId为空");
                throw new RuntimeException("questionId不能为空");
            }
            
            if (userAnswer == null) {
                System.out.println("错误：userAnswer为空");
                throw new RuntimeException("userAnswer不能为空");
            }
            
            Long questionId = Long.valueOf(questionIdObj.toString());
            
            // 获取题目详情
            Question question = questionRepository.findById(questionId)
                    .orElseThrow(() -> new RuntimeException("Question not found: " + questionId));
            
            // 获取正确答案选项
            List<QuestionOption> correctOptions = optionRepository.findByQuestionIdAndIsCorrectTrue(questionId);
            
            // 检查答案是否正确
            boolean isCorrect = false;
            List<String> correctAnswerTexts = new ArrayList<>();
            List<String> userAnswerTexts = new ArrayList<>();
            
            if (question.getType() == Question.QuestionType.SINGLE_CHOICE) {
                // 单选题
                Long selectedOptionId = Long.valueOf(userAnswer.toString());
                QuestionOption selectedOption = optionRepository.findById(selectedOptionId)
                        .orElse(null);
                
                if (selectedOption != null) {
                    userAnswerTexts.add(selectedOption.getContent());
                    isCorrect = correctOptions.stream()
                            .anyMatch(option -> option.getId().equals(selectedOptionId));
                }
                
                correctAnswerTexts = correctOptions.stream()
                        .map(QuestionOption::getContent)
                        .collect(Collectors.toList());
                        
            } else if (question.getType() == Question.QuestionType.MULTIPLE_CHOICE) {
                // 多选题
                @SuppressWarnings("unchecked")
                List<Long> selectedOptionIds = (List<Long>) userAnswer;
                Set<Long> correctIds = correctOptions.stream()
                        .map(QuestionOption::getId)
                        .collect(Collectors.toSet());
                Set<Long> selectedIds = new HashSet<>(selectedOptionIds);
                
                isCorrect = correctIds.equals(selectedIds);
                
                // 获取用户选择的选项文本
                for (Long optionId : selectedOptionIds) {
                    optionRepository.findById(optionId).ifPresent(option -> 
                        userAnswerTexts.add(option.getContent()));
                }
                
                // 获取正确答案文本
                correctAnswerTexts = correctOptions.stream()
                        .map(QuestionOption::getContent)
                        .collect(Collectors.toList());
            }
            
            if (isCorrect) {
                correctCount++;
            }
            
            // 构建分析结果
            Map<String, Object> analysisItem = new HashMap<>();
            analysisItem.put("questionId", questionId);
            analysisItem.put("isCorrect", isCorrect);
            analysisItem.put("correctAnswer", correctAnswerTexts);
            analysisItem.put("userAnswer", userAnswerTexts);
            analysisItem.put("explanation", question.getExplanation() != null ? 
                question.getExplanation() : "暂无解析");
            analysisItem.put("questionContent", question.getContent());
            analysisItem.put("questionType", question.getType().toString());
            analysis.add(analysisItem);
        }
        
        // 计算分数和正确率
        int score = totalCount > 0 ? (int) Math.round((double) correctCount / totalCount * 100) : 0;
        
        // 自动添加错题到错题本 - 暂时注释掉，方法未实现
        // try {
        //     addWrongQuestionsToBook(analysis, data);
        // } catch (Exception e) {
        //     System.err.println("添加错题到错题本失败: " + e.getMessage());
        //     // 不影响练习结果的返回
        // }
        
        Map<String, Object> result = new HashMap<>();
        result.put("score", score);
        result.put("correctCount", correctCount);
        result.put("totalCount", totalCount);
        result.put("timeSpent", data.get("timeSpent") != null ? data.get("timeSpent") : 0);
        result.put("analysis", analysis);
        
        System.out.println("=== 提交练习答案完成 ===");
        System.out.println("结果: " + result);
        
        return result;
        } catch (Exception e) {
            System.err.println("=== 提交练习答案出错 ===");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("提交练习答案失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Page<Map<String, Object>> getPracticeHistory(Pageable pageable) {
        // TODO: 实现真实的练习历史记录查询
        // 这里应该从数据库查询用户的练习历史记录
        // 暂时返回空列表，避免显示模拟数据
        List<Map<String, Object>> history = new ArrayList<>();
        
        return new org.springframework.data.domain.PageImpl<>(history, pageable, 0);
    }
    
    @Override
    public Map<String, Object> saveSearchHistory(Map<String, Object> data) {
        try {
            Long userId = Long.valueOf(data.get("userId").toString());
            String keyword = data.get("keyword").toString();
            String searchType = data.getOrDefault("searchType", "question").toString();
            Integer resultCount = data.get("resultCount") != null ? 
                Integer.valueOf(data.get("resultCount").toString()) : 0;
            
            SearchHistory searchHistory = SearchHistory.builder()
                .userId(userId)
                .keyword(keyword)
                .searchType(searchType)
                .resultCount(resultCount)
                .searchTime(LocalDateTime.now())
                .build();
            
            searchHistoryRepository.save(searchHistory);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "搜索记录保存成功");
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "搜索记录保存失败: " + e.getMessage());
            return result;
        }
    }
    
    @Override
    public Page<Map<String, Object>> getSearchHistory(Pageable pageable) {
        // 暂时使用固定用户ID，实际应该从认证信息中获取
        Long userId = 1L;
        Page<SearchHistory> historyPage = searchHistoryRepository.findByUserIdOrderBySearchTimeDesc(userId, pageable);
        
        return historyPage.map(history -> {
            Map<String, Object> historyMap = new HashMap<>();
            historyMap.put("id", history.getId());
            historyMap.put("keyword", history.getKeyword());
            historyMap.put("searchType", history.getSearchType());
            historyMap.put("resultCount", history.getResultCount());
            historyMap.put("searchTime", history.getSearchTime());
            return historyMap;
        });
    }
    
    @Override
    public List<Map<String, Object>> getRecentSearchHistory() {
        // 暂时使用固定用户ID，实际应该从认证信息中获取
        Long userId = 1L;
        List<SearchHistory> recentHistory = searchHistoryRepository.findTop10ByUserIdOrderBySearchTimeDesc(userId);
        
        return recentHistory.stream().map(history -> {
            Map<String, Object> historyMap = new HashMap<>();
            historyMap.put("id", history.getId());
            historyMap.put("keyword", history.getKeyword());
            historyMap.put("searchType", history.getSearchType());
            historyMap.put("resultCount", history.getResultCount());
            historyMap.put("searchTime", history.getSearchTime());
            return historyMap;
        }).collect(Collectors.toList());
    }
    
    @Override
    public Map<String, Object> clearSearchHistory() {
        try {
            // 暂时使用固定用户ID，实际应该从认证信息中获取
            Long userId = 1L;
            searchHistoryRepository.deleteByUserId(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "搜索记录清空成功");
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "搜索记录清空失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 将错题添加到错题本
     */
    private void addWrongQuestionsToBook(List<Map<String, Object>> analysis, Map<String, Object> data) {
        // 暂时使用固定用户ID，实际应该从认证信息中获取
        Long userId = 1L;
        String practiceSessionId = data.get("practiceId") != null ? 
            data.get("practiceId").toString() : "practice_" + System.currentTimeMillis();
        
        List<WrongQuestionDto> wrongQuestions = new ArrayList<>();
        
        for (Map<String, Object> analysisItem : analysis) {
            Boolean isCorrect = (Boolean) analysisItem.get("isCorrect");
            
            // 只添加错题
            if (!isCorrect) {
                Long questionId = Long.valueOf(analysisItem.get("questionId").toString());
                @SuppressWarnings("unchecked")
                List<String> userAnswerTexts = (List<String>) analysisItem.get("userAnswer");
                @SuppressWarnings("unchecked")
                List<String> correctAnswerTexts = (List<String>) analysisItem.get("correctAnswer");
                
                WrongQuestionDto wrongQuestionDto = WrongQuestionDto.builder()
                    .userId(userId)
                    .questionId(questionId)
                    .userAnswer(String.join(", ", userAnswerTexts))
                    .correctAnswer(String.join(", ", correctAnswerTexts))
                    .errorReason("练习中答错")
                    .isReviewed(false)
                    .practiceSessionId(practiceSessionId)
                    .build();
                
                wrongQuestions.add(wrongQuestionDto);
            }
        }
        
        if (!wrongQuestions.isEmpty()) {
            wrongQuestionService.addWrongQuestions(wrongQuestions);
            System.out.println("已添加 " + wrongQuestions.size() + " 道错题到错题本");
        }
    }
}
